import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';

class OrdersPage extends StatefulWidget {
  const OrdersPage({Key? key}) : super(key: key);

  @override
  State<OrdersPage> createState() => _OrdersPageState();
}

class _OrdersPageState extends State<OrdersPage> with TickerProviderStateMixin {
  final dio = Dio();
  List<dynamic> orders = [];
  bool isLoading = true;
  String? error;

  // 筛选状态
  String selectedStatus = 'all';
  String selectedType = 'all';

  // 动画控制器
  late AnimationController _refreshController;
  late Animation<double> _refreshAnimation;

  @override
  void initState() {
    super.initState();
    _setupAnimations();
    _loadOrders();
  }

  void _setupAnimations() {
    _refreshController = AnimationController(
      duration: const Duration(milliseconds: 1200),
      vsync: this,
    );
    _refreshAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _refreshController, curve: Curves.easeInOut),
    );
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  Future<void> _loadOrders() async {
    try {
      setState(() {
        isLoading = true;
        error = null;
      });

      // 构建查询参数
      Map<String, String> queryParams = {
        'page': '1',
        'limit': '50',
        'sortBy': 'createdAt',
        'sortOrder': 'desc',
      };

      if (selectedStatus != 'all') {
        queryParams['status'] = selectedStatus;
      }

      if (selectedType != 'all') {
        queryParams['productType'] = selectedType;
      }

      final token = await _getToken();
      final response = await dio.get(
        'http://127.0.0.1:5000/api/orders',
        queryParameters: queryParams,
        options: Options(
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            if (token != null) 'Authorization': token,
          },
        ),
      );

      if (response.statusCode == 200 && response.data['success']) {
        setState(() {
          orders = response.data['data'] ?? [];
          isLoading = false;
        });

        _refreshController.forward().then((_) {
          _refreshController.reset();
        });
      } else {
        throw Exception(response.data['message'] ?? '获取订单失败');
      }
    } catch (e) {
      print('加载订单失败: $e');
      setState(() {
        error = e.toString();
        isLoading = false;
      });
    }
  }

  Future<String?> _getToken() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final token = prefs.getString('auth_token');
      return token != null ? 'Bearer $token' : null;
    } catch (e) {
      print('获取token失败: $e');
      return null;
    }
  }

  Future<void> _cancelOrder(String orderId, String orderNumber) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('确认取消'),
            content: Text('确定要取消订单 $orderNumber 吗？'),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context, false),
                child: const Text('取消'),
              ),
              ElevatedButton(
                onPressed: () => Navigator.pop(context, true),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.red,
                  foregroundColor: Colors.white,
                ),
                child: const Text('确认取消'),
              ),
            ],
          ),
    );

    if (confirmed != true) return;

    try {
      final response = await dio.patch(
        'http://127.0.0.1:5000/api/orders/$orderId/cancel',
        data: {'cancellationReason': '用户主动取消'},
        options: Options(
          headers: {
            'Content-Type': 'application/json',
            'Authorization': await _getToken(),
          },
        ),
      );

      if (response.statusCode == 200 && response.data['success']) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('订单取消成功'),
            backgroundColor: Colors.green,
          ),
        );
        _loadOrders(); // 重新加载订单列表
      } else {
        throw Exception(response.data['message'] ?? '取消订单失败');
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('取消失败: ${e.toString()}'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  Future<void> _deleteOrder(String orderId, String orderNumber) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('确认删除'),
            content: Text('确定要删除订单 $orderNumber 吗？\n删除后无法恢复！'),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context, false),
                child: const Text('取消'),
              ),
              ElevatedButton(
                onPressed: () => Navigator.pop(context, true),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.red,
                  foregroundColor: Colors.white,
                ),
                child: const Text('确认删除'),
              ),
            ],
          ),
    );

    if (confirmed != true) return;

    try {
      final response = await dio.delete(
        'http://127.0.0.1:5000/api/orders/$orderId',
        options: Options(
          headers: {'Authorization': 'Bearer ${await _getToken()}'},
        ),
      );

      if (response.statusCode == 200 && response.data['success']) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('订单删除成功'),
            backgroundColor: Colors.green,
          ),
        );
        _loadOrders(); // 重新加载订单列表
      } else {
        throw Exception(response.data['message'] ?? '删除订单失败');
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('删除失败: ${e.toString()}'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  Widget _buildFilterChips() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          const Text(
            '订单状态',
            style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
          ),
          const SizedBox(height: 8),
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              children: [
                _buildFilterChip('全部', 'all', selectedStatus),
                _buildFilterChip('待确认', 'pending', selectedStatus),
                _buildFilterChip('已确认', 'confirmed', selectedStatus),
                _buildFilterChip('已完成', 'completed', selectedStatus),
                _buildFilterChip('已取消', 'cancelled', selectedStatus),
              ],
            ),
          ),
          const SizedBox(height: 12),
          const Text(
            '商品类型',
            style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
          ),
          const SizedBox(height: 8),
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              children: [
                _buildFilterChip('全部', 'all', selectedType),
                _buildFilterChip('旅游攻略', 'tour', selectedType),
                _buildFilterChip('酒店预订', 'hotel', selectedType),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFilterChip(String label, String value, String currentValue) {
    final isSelected = currentValue == value;
    return Padding(
      padding: const EdgeInsets.only(right: 8),
      child: FilterChip(
        label: Text(label),
        selected: isSelected,
        onSelected: (selected) {
          setState(() {
            if (label.contains('状态') ||
                ['全部', '待确认', '已确认', '已完成', '已取消'].contains(label)) {
              selectedStatus = value;
            } else {
              selectedType = value;
            }
          });
          _loadOrders();
        },
        selectedColor: Colors.blue.withOpacity(0.2),
        checkmarkColor: Colors.blue,
        labelStyle: TextStyle(
          color: isSelected ? Colors.blue : Colors.grey[600],
          fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
        ),
      ),
    );
  }

  Widget _buildOrderCard(Map<String, dynamic> order) {
    final productSnapshot = order['productSnapshot'] ?? {};
    final productType = order['productType'] ?? '';
    final isHotel = productType == 'hotel';
    final productName =
        isHotel
            ? (productSnapshot['name'] ?? '未知酒店')
            : (productSnapshot['title'] ?? '未知攻略');

    final orderNumber = order['orderNumber'] ?? '';
    final status = order['status'] ?? '';
    final totalPrice = order['totalPrice']?.toString() ?? '0';
    final currency = order['currency'] ?? '¥';

    final startDate =
        order['startDate'] != null
            ? DateTime.parse(order['startDate'])
            : DateTime.now();
    final endDate =
        order['endDate'] != null
            ? DateTime.parse(order['endDate'])
            : DateTime.now();

    final createdAt =
        order['createdAt'] != null
            ? DateTime.parse(order['createdAt'])
            : DateTime.now();

    Color statusColor = _getStatusColor(status);
    String statusText = _getStatusText(status);

    return AnimatedBuilder(
      animation: _refreshAnimation,
      builder: (context, child) {
        return Transform.translate(
          offset: Offset(0, 20 * (1 - _refreshAnimation.value)),
          child: Opacity(opacity: _refreshAnimation.value, child: child),
        );
      },
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: Colors.grey.withOpacity(0.1),
              spreadRadius: 1,
              blurRadius: 6,
              offset: const Offset(0, 3),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 订单头部
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.grey[50],
                borderRadius: const BorderRadius.only(
                  topLeft: Radius.circular(12),
                  topRight: Radius.circular(12),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '订单号：$orderNumber',
                        style: const TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w600,
                          color: Colors.black87,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        DateFormat('yyyy-MM-dd HH:mm').format(createdAt),
                        style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                      ),
                    ],
                  ),
                  Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 12,
                      vertical: 6,
                    ),
                    decoration: BoxDecoration(
                      color: statusColor,
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: Text(
                      statusText,
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ],
              ),
            ),

            // 商品信息
            Padding(
              padding: const EdgeInsets.all(16),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 商品图片
                  Container(
                    width: 80,
                    height: 80,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8),
                      color: Colors.grey[200],
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: Image.network(
                        isHotel
                            ? (productSnapshot['mainImage'] ??
                                productSnapshot['image'] ??
                                '')
                            : (productSnapshot['image'] ?? ''),
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stackTrace) {
                          return Container(
                            color: Colors.grey[200],
                            child: Icon(
                              isHotel ? Icons.hotel : Icons.map,
                              color: Colors.grey[400],
                              size: 32,
                            ),
                          );
                        },
                      ),
                    ),
                  ),

                  const SizedBox(width: 12),

                  // 商品详情
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          productName,
                          style: const TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                            color: Colors.black87,
                          ),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                        const SizedBox(height: 8),

                        Row(
                          children: [
                            Icon(
                              isHotel ? Icons.hotel : Icons.tour,
                              size: 16,
                              color: Colors.blue,
                            ),
                            const SizedBox(width: 4),
                            Text(
                              isHotel ? '酒店预订' : '旅游攻略',
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.grey[600],
                              ),
                            ),
                          ],
                        ),

                        const SizedBox(height: 8),

                        Row(
                          children: [
                            Icon(
                              Icons.calendar_today,
                              size: 16,
                              color: Colors.grey[600],
                            ),
                            const SizedBox(width: 4),
                            Text(
                              isHotel
                                  ? '${DateFormat('MM-dd').format(startDate)} 至 ${DateFormat('MM-dd').format(endDate)}'
                                  : '${DateFormat('yyyy-MM-dd').format(startDate)}',
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.grey[600],
                              ),
                            ),
                          ],
                        ),

                        const SizedBox(height: 12),

                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              '$currency$totalPrice',
                              style: const TextStyle(
                                fontSize: 18,
                                fontWeight: FontWeight.bold,
                                color: Colors.red,
                              ),
                            ),

                            if (status == 'pending' || status == 'confirmed')
                              Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  OutlinedButton(
                                    onPressed:
                                        () => _cancelOrder(
                                          order['_id'],
                                          orderNumber,
                                        ),
                                    style: OutlinedButton.styleFrom(
                                      side: const BorderSide(color: Colors.red),
                                      foregroundColor: Colors.red,
                                      padding: const EdgeInsets.symmetric(
                                        horizontal: 12,
                                        vertical: 8,
                                      ),
                                    ),
                                    child: const Text(
                                      '取消',
                                      style: TextStyle(fontSize: 12),
                                    ),
                                  ),
                                ],
                              ),

                            if (status == 'cancelled' || status == 'completed')
                              OutlinedButton(
                                onPressed:
                                    () =>
                                        _deleteOrder(order['_id'], orderNumber),
                                style: OutlinedButton.styleFrom(
                                  side: BorderSide(color: Colors.grey[400]!),
                                  foregroundColor: Colors.grey[600],
                                  padding: const EdgeInsets.symmetric(
                                    horizontal: 12,
                                    vertical: 8,
                                  ),
                                ),
                                child: const Text(
                                  '删除',
                                  style: TextStyle(fontSize: 12),
                                ),
                              ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Color _getStatusColor(String status) {
    switch (status) {
      case 'pending':
        return Colors.orange;
      case 'confirmed':
        return Colors.blue;
      case 'completed':
        return Colors.green;
      case 'cancelled':
        return Colors.red;
      case 'refunded':
        return Colors.purple;
      default:
        return Colors.grey;
    }
  }

  String _getStatusText(String status) {
    switch (status) {
      case 'pending':
        return '待确认';
      case 'confirmed':
        return '已确认';
      case 'completed':
        return '已完成';
      case 'cancelled':
        return '已取消';
      case 'refunded':
        return '已退款';
      default:
        return '未知状态';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      body: CustomScrollView(
        slivers: [
          // AppBar
          SliverAppBar(
            expandedHeight: 120,
            floating: false,
            pinned: true,
            backgroundColor: Colors.blue,
            foregroundColor: Colors.white,
            flexibleSpace: FlexibleSpaceBar(
              title: const Text(
                '我的订单',
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
              ),
              background: Container(
                decoration: const BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [Color(0xFF1976D2), Color(0xFF42A5F5)],
                  ),
                ),
                child: const Center(
                  child: Icon(
                    Icons.receipt_long,
                    size: 48,
                    color: Colors.white70,
                  ),
                ),
              ),
            ),
            actions: [
              IconButton(
                icon: const Icon(Icons.refresh),
                onPressed: _loadOrders,
              ),
            ],
          ),

          // 筛选器
          SliverToBoxAdapter(child: _buildFilterChips()),

          // 订单列表
          if (isLoading)
            const SliverToBoxAdapter(
              child: Center(
                child: Padding(
                  padding: EdgeInsets.all(32),
                  child: CircularProgressIndicator(),
                ),
              ),
            )
          else if (error != null)
            SliverToBoxAdapter(
              child: Center(
                child: Padding(
                  padding: const EdgeInsets.all(32),
                  child: Column(
                    children: [
                      const Icon(
                        Icons.error_outline,
                        size: 64,
                        color: Colors.red,
                      ),
                      const SizedBox(height: 16),
                      Text(
                        '加载失败',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.w600,
                          color: Colors.grey[800],
                        ),
                      ),
                      const SizedBox(height: 8),
                      Text(
                        error!,
                        style: TextStyle(color: Colors.grey[600]),
                        textAlign: TextAlign.center,
                      ),
                      const SizedBox(height: 16),
                      ElevatedButton(
                        onPressed: _loadOrders,
                        child: const Text('重试'),
                      ),
                    ],
                  ),
                ),
              ),
            )
          else if (orders.isEmpty)
            SliverToBoxAdapter(
              child: Center(
                child: Padding(
                  padding: const EdgeInsets.all(32),
                  child: Column(
                    children: [
                      Icon(
                        Icons.shopping_bag_outlined,
                        size: 80,
                        color: Colors.grey[300],
                      ),
                      const SizedBox(height: 16),
                      Text(
                        '暂无订单',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.w600,
                          color: Colors.grey[600],
                        ),
                      ),
                      const SizedBox(height: 8),
                      Text('快去下单吧～', style: TextStyle(color: Colors.grey[500])),
                    ],
                  ),
                ),
              ),
            )
          else
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (context, index) => _buildOrderCard(orders[index]),
                childCount: orders.length,
              ),
            ),
        ],
      ),
    );
  }
}
